#ifndef STATEUPDATETHROTTLER_H
#define STATEUPDATETHROTTLER_H

#include <QObject>
#include <QTimer>
#include <QQueue>
#include <QMutex>
#include <QDebug>

/**
 * StateUpdateThrottler - 状态更新节流器
 * 
 * 防止状态更新过于频繁，提供防抖和节流功能
 * 确保UI更新的性能和流畅性
 */
class StateUpdateThrottler : public QObject
{
    Q_OBJECT

public:
    // 状态更新请求结构
    struct StateUpdateRequest {
        QString type;
        QVariant data;
        QDateTime timestamp;
        int priority = 0; // 优先级，数字越小优先级越高
        
        StateUpdateRequest(const QString& requestType, const QVariant& requestData, int requestPriority = 0)
            : type(requestType), data(requestData), priority(requestPriority), timestamp(QDateTime::currentDateTime()) {}
        
        bool operator<(const StateUpdateRequest& other) const {
            return priority < other.priority;
        }
    };

public:
    explicit StateUpdateThrottler(QObject* parent = nullptr);
    ~StateUpdateThrottler();
    
    // 配置方法
    void setThrottleInterval(int intervalMs);
    void setMaxQueueSize(int maxSize);
    void setEnabled(bool enabled);
    
    // 状态更新请求
    void requestStateUpdate(const StateUpdateRequest& request);
    void requestStateUpdate(const QString& type, const QVariant& data, int priority = 0);
    
    // 队列管理
    void clearQueue();
    int queueSize() const;
    bool isProcessing() const;

signals:
    void stateUpdateRequested(const StateUpdateRequest& request);
    void queueOverflow();
    void processingStarted();
    void processingFinished();

private slots:
    void processPendingUpdates();

private:
    // 处理更新请求
    void processUpdateRequest(const StateUpdateRequest& request);
    
    // 队列管理
    void addToQueue(const StateUpdateRequest& request);
    StateUpdateRequest dequeueRequest();
    void sortQueueByPriority();

private:
    // 配置
    int m_throttleIntervalMs = 50;  // 50ms防抖
    int m_maxQueueSize = 100;
    bool m_enabled = true;
    
    // 队列和定时器
    QQueue<StateUpdateRequest> m_pendingUpdates;
    QTimer* m_throttleTimer;
    QMutex m_queueMutex;
    
    // 状态跟踪
    bool m_isProcessing = false;
    QDateTime m_lastUpdateTime;
};

#endif // STATEUPDATETHROTTLER_H
